package top.z.work.framework.orm.config;

import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.keygen.KeyGeneratorFactory;
import com.mybatisflex.core.keygen.impl.SnowFlakeIDKeyGenerator;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@MapperScan("top.z.work.module.*.mapper")
public class OrmConfig implements MyBatisFlexCustomizer {

    @Value("${top-work.id-worker.workerId}")
    Integer workerId;
    @Value("${top-work.id-worker.centerId}")
    Integer centerId;
    @Value("${top-work.id-worker.start-time}")
    Long    startTime;

    /**
     * 配置默认ID生成
     */
    @PostConstruct
    public void configKeyGenerator() {
        log.info("workerId: {}, centerId: {}, startTime: {}", workerId, centerId, startTime);
        // 设置全局ID生成策略
        SnowFlakeIDKeyGenerator snowFlakeIDKeyGenerator = new SnowFlakeIDKeyGenerator(workerId, centerId);
        SnowFlakeIDKeyGenerator.setTwepoch(startTime);
        KeyGeneratorFactory.register("snowflakeIdGenerator", snowFlakeIDKeyGenerator);

        FlexGlobalConfig.KeyConfig keyConfig = new FlexGlobalConfig.KeyConfig();
        keyConfig.setBefore(true);
        keyConfig.setKeyType(KeyType.Generator);
        keyConfig.setValue("snowflakeIdGenerator");
        FlexGlobalConfig.getDefaultConfig().setKeyConfig(keyConfig);
    }

    @Override
    public void customize(FlexGlobalConfig config) {
        // 开启审计功能
        AuditManager.setAuditEnable(true);
        // 设置 SQL 审计收集器
        AuditManager.setMessageCollector(message -> log.info("execution time: {}ms, sql: [{}]", message.getElapsedTime(), message.getFullSql()));
    }
}
